package stu.aistar.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import stu.aistar.mapper.UserMapper;
import stu.aistar.model.pojo.User;
import stu.aistar.model.vo.Result;
import stu.aistar.service.UserService;
import stu.aistar.util.CheckInfoUtil;

import java.io.IOException;
import java.util.List;

@RequestMapping("/excel")
@RestController
public class ExcelController {
    @Autowired
    private UserService userService;
    @PostMapping("/importUsers")
    public Result importExcel2(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        //表格标题行数,默认0
        importParams.setHeadRows(1);
        //表头行数
        importParams.setTitleRows(1);
        Result res;
        Integer total=0;
        try {
            ExcelImportResult<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class, importParams);
            List<User> userList = result.getList();
            for (User user : userList) {
                //过滤不符合条件的数据
                if(null!=user&&userService.findUserByPhone(user.getPhone())==null){
                    if(CheckInfoUtil.CheckMobilePhoneNum(user.getPhone())&&CheckInfoUtil.isValidEmail(user.getEmail())){
                        userService.insertUserByImport(user);
                        total +=1;
                    }

                }
            }
        } catch (IOException e) {
           e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if(total == 0){
            res = new Result("404","未插入数据",null);
        }else {
            res = new Result("200","成功导入"+total+"条数据",null);
        }

        return res;
    }

}
